package com.lty.jeeg.server.modules.fas.controller;

import com.lty.jeeg.server.common.annotation.LogAnnotation;
import com.lty.jeeg.server.common.dto.ResponseInfo;
import com.lty.jeeg.server.common.enums.ResponseEnum;
import com.lty.jeeg.server.common.excel.EasyExcelUtil;
import com.lty.jeeg.server.common.utils.BeanConverter;
import com.lty.jeeg.server.common.utils.DateUtils;
import com.lty.jeeg.server.common.utils.ResponseUtil;
import com.lty.jeeg.server.modules.fas.dto.StockDTO;
import com.lty.jeeg.server.modules.fas.export.GoodsExportEntity;
import com.lty.jeeg.server.modules.fas.export.StockExportEntity;
import com.lty.jeeg.server.modules.fas.export.StockExportEntityDP;
import com.lty.jeeg.server.modules.fas.export.StockImportEntityDP;
import com.lty.jeeg.server.modules.fas.vo.StockVO;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.lty.jeeg.server.common.page.table.PageTableRequest;
import com.lty.jeeg.server.common.page.table.PageTableResponse;

import com.lty.jeeg.server.modules.fas.model.Stock;
import com.lty.jeeg.server.modules.fas.service.StockService;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author : LTY
 * @date : 2019-02-13 10:11:33
 * Description : 库存统计
 */
@Api(tags = "库存统计")
@RestController
@RequestMapping("/stock")
public class StockController {

    private final StockService stockService;

    @Autowired
    public StockController(StockService stockService) {

        this.stockService = stockService;
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取")
    public ResponseInfo get(@PathVariable Long id) {

        return ResponseUtil.success(stockService.getById(id));
    }

    @PostMapping
    @ApiOperation(value = "保存")
    @RequiresPermissions(value={"fas:stock:add","fas:stockD:add","fas:stockP:add"},logical =Logical.OR )
    public ResponseInfo save(@RequestBody Stock stock) {

        return ResponseUtil.success(stockService.save(stock));
    }

    @PutMapping
    @ApiOperation(value = "修改")
    @RequiresPermissions(value = {"fas:stock:edit","fas:stockD:edit","fas:stockP:edit"},logical = Logical.OR)
    public ResponseInfo update(@RequestBody Stock stock) {

        return ResponseUtil.success(stockService.update(stock));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除")
    @RequiresPermissions(value = {"fas:stock:del","fas:stockD:del","fas:stockP:del"},logical = Logical.OR)
    public ResponseInfo delete(@PathVariable Long id) {

        return ResponseUtil.success(stockService.delete(id));
    }

    @GetMapping("/list")
    @ApiOperation(value = "列表")
    @RequiresPermissions(value={"fas:stock:query","fas:stockP:query","fas:stockD:query"},logical=Logical.OR)
    public PageTableResponse list(PageTableRequest request){

        return stockService.list(request);
    }

    @PutMapping( "/updateIdle")
    @ApiOperation("修改闲置数量")
    public ResponseInfo updateIdle(HttpServletRequest request, HttpServletResponse response) {
        ResponseEnum em=stockService.updateIdle(request);
        if(em.getCode()==0) {
            return ResponseUtil.success(em);
        }else{
            return ResponseUtil.error(em);
        }
    }

    @LogAnnotation
    @PostMapping("/export/{type2}")
    @ApiOperation(value = "库存列表导出")
    @RequiresPermissions(value={"fas:stockP:export","fas:stockD:export","fas:stock:export"})
    public void export(@PathVariable Integer type2, StockVO stockVO, HttpServletResponse response) {
        String type = stockVO.getType();
        StockDTO stockDTO = new StockDTO();

        if(StringUtils.isNotEmpty(type)){
            String fileNameStart = "个人库存明细导出";
            String sheetName = "个人库存明细列表";
            if("dept".equals(type)){
                fileNameStart = "部门库存明细导出";
                sheetName = "部门库存明细列表";
            }else if("admin".equals(type)){
                fileNameStart = "行政仓库存明细导出";
                sheetName = "行政仓库存明细列表";
                type2 = 2;
            }else if("discard".equals(type)){
                fileNameStart = "报废仓库存明细导出";
                sheetName = "报废仓库存明细列表";
                type2 = 3;
            }
            String fileName = fileNameStart+ DateUtils.getDateTime("yyyyMMddHHmmss");
            stockDTO.setType(type);
            if (type2 == 1) {
                //导出数据
                stockDTO = BeanConverter.map(stockVO, StockDTO.class);
                List<StockExportEntityDP> dataList = stockService.getExportDatasDP(stockDTO);
                EasyExcelUtil.writeExcel(response, dataList, fileName, sheetName, new StockExportEntityDP());
            }else if(type2 ==2){
                //导出数据--行政仓
                stockDTO = BeanConverter.map(stockVO, StockDTO.class);
                List<StockExportEntityDP> dataList = stockService.getExportDatasDP(stockDTO);
                EasyExcelUtil.writeExcel(response, dataList, fileName, sheetName, new StockExportEntityDP());
            }else if(type2 == 3){
                //导出数据--报废仓
                stockDTO = BeanConverter.map(stockVO, StockDTO.class);
                List<StockExportEntityDP> dataList = stockService.getExportDatasDP(stockDTO);
                EasyExcelUtil.writeExcel(response, dataList, fileName, sheetName, new StockExportEntityDP());
            }else{
                List<StockImportEntityDP> dataList = new ArrayList<>();
                EasyExcelUtil.writeExcel(response, dataList, "库存明细导入模板", "库存明细导入模板", new StockImportEntityDP());
            }
        }else{
            //库存合计导出
            String fileNameStart = "库存合计列表导出";
            String sheetName = "库存合计列表";
            List<StockExportEntity> dataList = stockService.getExportDatas(stockDTO);
            String fileName = fileNameStart+ DateUtils.getDateTime("yyyyMMddHHmmss");
            EasyExcelUtil.writeExcel(response, dataList, fileName, sheetName, new StockExportEntity());
        }
    }


    /**
     * 库存导入
     * xuchen
     * @param file
     * @param response
     */
    @LogAnnotation
    @PostMapping("/importData")
    @ApiOperation(value = "商品导入")
    @RequiresPermissions("fas:stock:importData")
    public HashMap<String, Object> importData(MultipartFile file , HttpServletResponse response) {

        //创建返回前端map对象
        HashMap<String, Object> hashMap = new HashMap<>();
        //excel数据
        List<Object> stockList = EasyExcelUtil.readExcel(file, new StockImportEntityDP());
        //导入失败数据
        List<StockImportEntityDP> failList = stockService.importData(stockList);
        if(failList != null && failList.size() > 0){
            String fileName = "importFailData"+DateUtils.getDateTime("yyyyMMddHHmmss");
            //1.创建一个excel对象
            HSSFWorkbook excel = new HSSFWorkbook();
            //单元格样式
            HSSFCellStyle cellStyle = excel.createCellStyle();
            HSSFCellStyle fontStyle = excel.createCellStyle();
            //字体样式
            HSSFFont font = excel.createFont();
            fontStyle.setFont(font);
            //2.在excel中添加一个sheet
            HSSFSheet sheet = excel.createSheet("导入失败信息");
            //创建第一行，开始写表头
            HSSFRow row = sheet.createRow(0);
            HSSFCell cell = row.createCell(0);
            //第一列
            cell = row.createCell(0);
            cell.setCellValue("商品编码");
            cell.setCellStyle(cellStyle);
            //第二列
            cell = row.createCell(1);
            cell.setCellValue("商品名称");
            cell.setCellStyle(cellStyle);
            //第三列
            cell = row.createCell(2);
            cell.setCellValue("所属人员名称");
            cell.setCellStyle(cellStyle);
            //第四列
            cell = row.createCell(3);
            cell.setCellValue("所属部门名称");
            cell.setCellStyle(cellStyle);
            //第五列
            cell = row.createCell(4);
            cell.setCellValue("所属公司名称");
            cell.setCellStyle(cellStyle);
            //第六列
            cell = row.createCell(5);
            cell.setCellValue("总数量");
            cell.setCellStyle(cellStyle);
            //第七列
            cell = row.createCell(6);
            cell.setCellValue("错误信息");
            cell.setCellStyle(cellStyle);


            //5.写入数据
            for (int i = 0; i < failList.size(); i++) {
                //在excel中新增一行
                row = sheet.createRow(i + 1);//表头已占一行，故从第二行开始添加数据
                //在新增的一行中，依次创建单元格放入上面定义的列值
                row.createCell(0).setCellValue(failList.get(i).getGoodsCode());//商品编码
                row.createCell(1).setCellValue(failList.get(i).getGoodsName());//商品名称
                row.createCell(2).setCellValue(failList.get(i).getUserName());//所属用户
                row.createCell(3).setCellValue(failList.get(i).getDeptName());//所属部门
                row.createCell(4).setCellValue(failList.get(i).getCompanyName());//所属公司
                row.createCell(5).setCellValue(failList.get(i).getTotalNumber());//总数量
                row.createCell(6).setCellValue(failList.get(i).getFailMsg());//错误信息
            }
            //6.将其生成一个excel文件，输出
            String filePath ="importFail"+File.separatorChar+fileName+".xls";
            //失败信息excel文件的file对象
            File file2 = new File(filePath);
            try{
                FileOutputStream fileOs = new FileOutputStream(file2);
                excel.write(fileOs);
                fileOs.close();
                String file2Name = file2.getName();
                hashMap.put("fileName",file2Name);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        hashMap.put("failNum",failList.size());
        hashMap.put("successNum",stockList.size() - failList.size());
        return hashMap;
    }

}
